#

import smtplib
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication


class SendEmailHandler(object):

    def __init__(self, smtp_host, smtp_port, pass_word, send_addr):
        # 发送邮件的smtp服务器
        self.smtp_host = smtp_host
        # 授权码，和用户名user一起，用于登录smtp， 非邮箱密码
        self.smtp_pwd = pass_word
        # smtp服务器SSL端口号，默认是465
        self.smtp_port = smtp_port
        # 发送者邮箱账号
        self.send_addr = send_addr

    """
        :param subject: 标题
        :param content: 内容 html text
        :param attachment_list: 附件地址集合 目前支持zip png pdf
        :param to_user_list: 发送邮件人集合
        :param is_html: True 是html False不是
        :return: 无
    """
    def send_email(self, to_user_list, subject='', content='', attachment_list=[], is_html=False):
        if not to_user_list or len(to_user_list) < 1:
            raise Exception("发送用户为空!!")
        if not content or content.strip() == "":
            raise Exception("邮件标题不能为空!!")
        if not subject or content.strip() == "":
            raise Exception("邮件内容不能为空!!")
        # 构建msg对象
        msg = MIMEMultipart()
        # 设置发送邮箱
        msg['from'] = self.send_addr
        # 设置发送方
        msg['to'] = ",".join(to_user_list)
        # 设置标题
        msg['subject'] = subject
        # 设置邮件内容
        if is_html:
            html = MIMEText(content, _subtype="html", _charset="utf-8")
            msg.attach(html)
        else:
            text = MIMEText(content, _subtype='plain', _charset='utf-8')
            msg.attach(text)
        # 设置附件
        if attachment_list:
            for attachment in attachment_list:
                if str(attachment).endswith(".png"):
                    # png
                    with open(attachment, 'rb') as f:
                        image_attachment = MIMEImage(f.read(), attachment.split('.')[-1])
                        file_name = attachment[str(attachment).rfind("//") + 2:len(attachment)]
                        image_attachment.add_header('Content-Disposition', 'attachment', filename=file_name)
                        msg.attach(image_attachment)
                elif str(attachment).endswith(".pdf") or str(attachment).endswith(".zip"):
                    # pfd
                    with open(attachment, 'rb') as f:
                        pdf_attachment = MIMEApplication(f.read())
                        file_name = attachment[str(attachment).rfind("//") + 2:len(attachment)]
                        pdf_attachment.add_header('Content-Disposition', 'attachment', filename=file_name)
                        msg.attach(pdf_attachment)
        try:
            # 实例化一个SMTP_SSL对象
            client = smtplib.SMTP(self.smtp_host, self.smtp_port)
            # client.set_debuglevel(1)
            # 登录到邮件服务器
            login_resp = client.login(self.send_addr, self.smtp_pwd)
            print(f"登录服务器结果:{login_resp}")
            if login_resp and login_resp[0] == 235:
                print(f"登录成功code:{login_resp[0]}")
                resp = client.send_message(msg, self.send_addr, to_user_list)
                print(f"mail has been send successfully. message:{str(resp)}")
            else:
                print(f"登录到邮件服务器失败:{login_resp}")
        except Exception as e:
            print(e)
        finally:
            if client:
                client.quit()


if __name__ == '__main__':
    smtp_host = "smtp.163.com"
    smtp_port = 25
    smtp_user = "ktajax@163.com"
    pass_word = "XCABBMHJGDALLOSB"
    handler = SendEmailHandler(smtp_host=smtp_host, smtp_port=smtp_port, pass_word=pass_word,
                               send_addr=smtp_user)

    toSendEmailLst = ['zxcxueqi520@163.com']
    subject = "这是来自Python的测试邮件"
    content = '''<p>Python 邮件发送测试...</p>
                <p><a href="http://www.baidu.com">这是一个神奇的链接啊</a></p>
              '''
    # 模拟附件 项目中直接读取服务器url
    attachment_list = ['D://workspace//learn-demo//springcloud.pdf', 'D://workspace//learn-demo//springcloud.png',
                       'D://workspace//learn-demo//测试.zip']
    handler.send_email(to_user_list=toSendEmailLst, subject=subject, content=content,
                       attachment_list=attachment_list, is_html=True)
